class MediaController < ApplicationController
  layout "main", :except => [:edit, :delete, :delete_reason]
  before_filter :login_required, :except => [:show, :list, :random, :index, :search, :json_menu]
  require_role ['Administrator', 'Moderator', 'Uploader'], :only => [:create, :new]
  require_role ['Administrator', 'Moderator'], :only => [:destroy, :edit, :update], :unless => "current_user.id == Media.find(params[:id]).user_id"
  require_role ['Administrator', 'Moderator'], :only => [:undestroy]
  session :cookie_only => false, :only => :create
  def index
    @mediatags = Media.tag_counts(:order => 'count desc', :limit => 25, :conditions => 'deleted_at is NULL and upload_complete = 1')
    @mediasbyrating = Media.find(:all, :limit => 10, :order => 'rating desc', :conditions => 'deleted_at is NULL and upload_complete = 1')
    @mediasbyviews = Media.find(:all, :limit => 10, :include => :viewing, :order => 'viewings.views desc', :conditions => 'deleted_at is NULL and upload_complete = 1')
    @mediaslatest = Media.find(:all, :limit => 10, :order => 'created_at desc', :conditions => 'deleted_at is NULL and upload_complete = 1')
    @mediasrandom = Media.find(:all, :limit => 10, :order => 'RAND()', :conditions => 'deleted_at is NULL and upload_complete = 1')
  end
  
  def new
    @media = Media.new
  end
  
  def json_menu
    categories = []
    Category.find(:all).each do |category|
      categories << {
          "name" => category.name,
          "url" => url_for({:controller => 'media', :action => 'list', :category => category.id, :permalink => category.permalink}),
          "subnav" => nil
        }
    end
    json_array = {
      "config"=>{
        "paddingRight"=>10,
        "rightArrow"=>"/images/bg_menu_right_arrow.gif",
        "linkPaddingTopBottom"=>2,
        "popupBorderSize"=>1,
        "backgroundHover"=>"#D9E1E5 url(/images/nav.gif) left bottom",
        "background"=>"#D9E1E5 url(/images/nav.gif)",
        "popupWidth"=>140,
        "popupPaddingRight"=>10,
        "fontSize"=>12,
        "lineHeight"=>26,
        "borderSizeBottom"=>0,
        "borderSizeRight"=>1,
        "border"=>"solid #AFBEC7",
        "padding"=>5,
        "downArrow"=>"/images/bg_menu_down_arrow.gif",
        "popupLineHeight"=>25,
        "marginBottom"=>5,
        "linkPaddingLeftRight"=>5,
        "borderSizeTop"=>0,
        "popupPadding"=>5,
        "fontColor"=>"#456",
        "borderSizeLeft"=>0,
        "width"=>120
      },
      "menus"=> [
        {
          "name"=>"Random Media",
          "url"=>url_for({:controller => '/media', :action => 'random'}),
          "subnav"=>nil
        },
        {
          "name"=>"Browse Media",
          "url"=>url_for({:controller => '/media', :action => 'list'}),
          "subnav"=>nil
        },
        {
          "name"=>"Categories",
          "url"=>"",
          "subnav"=> categories
        }
      ]
    }
    render :text => 'menuJSON = '+json_array.to_json
  end

  def moviestatus
    @media = Media.find(params[:id])
    render :partial => "video", :locals => { :media => @media, :secondrun => params[:secondrun] }
  end
  
  def create
    if params[:Filedata]
      params[:data] = {}
      params[:data][:uploaded_data] = params[:Filedata]
      params[:data][:uploaded_data].content_type = File.mime_type?(params[:data][:uploaded_data].original_filename)
      logger.info("file is #{params[:data][:uploaded_data].content_type}")
      logger.info("file is #{params[:data][:uploaded_data].inspect}")
      if params[:data][:uploaded_data].content_type =~ /image\/.*/
        @image_file = ImageFile.create(params[:data])
        if @image_file.save
          render :text => "#{@image_file.id},ImageFile"
        else
          render :text => @image_file.errors.inspect
        end
      elsif params[:data][:uploaded_data].content_type =~ /video\/.*/ or params[:data][:uploaded_data].content_type == "audio/x-ms-wmv"
        @video_file = VideoFile.create(params[:data])
        if @video_file.save
          video_info = RVideo::Inspector.new(:file => @video_file.full_filename)
          if (video_info.width > 500)
            do_video_conversion(true)
            @video_file.update_attributes(:quality => "high")
          else
            do_video_conversion(false)
            @video_file.update_attributes(:quality => "low")
          end
          render :text => "#{@video_file.id},VideoFile"
        else
          render :text => @video_file.errors.inspect
        end
      end
    elsif params[:hidFileID]
      params[:media][:user_id]=current_user.id
        @fileid, @filetype = params[:hidFileID].split(',')
        @file = @filetype.constantize.find(@fileid)
        @media = @file.create_media(params[:media])
        @media.tag_list = params[:media][:tag_list]
        if @media.save
          if @file.save
            if @filetype == "ImageFile"
              @media.update_attributes(:upload_complete => 1)
            end
            flash[:notice] = 'Media was successfully created.'
            redirect_to :action => :show, :id => @media.id, :permalink => @media.permalink
          else
            @media = Media.find(@media.id)
            @file.destroy
            @media.destroy
            flash[:warning] = 'Media could not be saved.'
            render :action => :new
          end
        else
          render :action => :new
        end
    else
    params[:media][:user_id]=current_user.id
      if params[:data][:uploaded_data].content_type =~ /image\/.*/
        @image_file = ImageFile.new(params[:data])
        logger.info("file is #{params[:data][:uploaded_data].content_type}")
        @media = @image_file.create_media(params[:media])
        @media.tag_list = params[:media][:tag_list]
        if @media.save
          if @image_file.save
            @media.update_attributes(:upload_complete => 1)
            flash[:notice] = 'Media was successfully created.'
            redirect_to :action => :show, :id => @media.id, :permalink => @media.permalink
          else
            @media = Media.find(@media.id)
            @media.destroy
            flash[:warning] = 'Media could not be saved.'
            render :action => :new
          end
        else
          render :action => :new
        end
      elsif params[:data][:uploaded_data].content_type =~ /video\/.*/ or params[:data][:uploaded_data].content_type == "audio/x-ms-wmv"
        @video_file = VideoFile.new(params[:data])
        logger.info("file is #{params[:data][:uploaded_data].content_type}")
        @media = @video_file.create_media(params[:media])
        @media.tag_list = params[:media][:tag_list]
        if @media.save
          if @video_file.save
          video_info = RVideo::Inspector.new(:file => @video_file.full_filename)
            if (video_info.width > 400)
              @video_file.update_attributes(:quality => "high")
              do_video_conversion(true)
            else
              @video_file.update_attributes(:quality => "low")
              do_video_conversion(false)
            end
            flash[:notice] = 'Media was successfully created.'
            redirect_to :action => :show, :id => @media.id, :permalink => @media.permalink
          else
            @media = Media.find(@media.id)
            @media.destroy
            flash[:warning] = 'Media could not be saved.'
            render :action => :new
          end
        else
          render :action => :new
        end
      end
    end
  end
  
  def show
    @media = Media.find(params[:id])
    @media.increment_views
    @page_title = clean_text(@media.title)
    if logged_in? and current_user.has_role?(['Administrator', 'Moderator'])
      @comments = Comment.find(:all, :conditions => ["media_id = ?", params[:id]], :order => 'root_id asc, lft')
    else
      @comments = Comment.find(:all, :conditions => ["media_id = ? and deleted_at is null and purged_at is null", params[:id]], :order => 'root_id asc, lft')
    end
    @comment_threshold = -4
  end
  
  def preview
    @content = params[:content]
    render :partial => "preview"
  end

  def change_rating
    if current_user
      @media = Media.find(params[:id], :include => [:media_rating_logs])
      if has_not_rated_media?(@media)
        if params[:direction] == "down"
          new_rating = @media[:rating] - 1
          @media.update_attributes(:rating => new_rating)
          MediaRatingLog.new(:user_id => current_user.id, :media_id => @media[:id], :value => '-1').save
        else
          if params[:direction] == "up"
            new_rating = @media[:rating] + 1
            @media.update_attributes(:rating => new_rating)
            MediaRatingLog.new(:user_id => current_user.id, :media_id => @media[:id], :value => '1').save
          end
        end
      end
    end
    @media = Media.find(params[:id], :include => [:media_rating_logs])
    render(:partial => 'rating')
  end
  def delete
    @media = Media.find(params[:id])
  end
  def delete_reason
    @media = Media.find(params[:id])
  end
  def destroy
    @media = Media.find(params[:id])
    if @media.update_attributes(:deleted_by => current_user.id, :deleted_at => Time.now(), :deleted_reason => params[:media][:deleted_reason])
      flash[:notice] = 'Media was successfully deleted.'
      redirect_back_or_default :controller => '/media', :action => 'show', :id => params[:id], :permalink => @media.permalink
    else
      flash[:notice] = 'Comment was not deleted.'
      redirect_back_or_default :controller => '/media', :action => 'show', :id => params[:id], :permalink => @media.permalink
    end
  end
  def undestroy
    @media = Media.find(params[:id])
    if @media.update_attributes(:deleted_by => nil, :deleted_at => nil, :deleted_reason => nil)
      flash[:notice] = 'Media was successfully undeleted.'
      redirect_back_or_default :controller => '/media', :action => 'show', :id => params[:id], :permalink => @media.permalink
    else
      flash[:notice] = 'Comment was not undeleted.'
      redirect_back_or_default :controller => '/media', :action => 'show', :id => params[:id], :permalink => @media.permalink
    end
  end
  def edit
    @media = Media.find(params[:id])
  end
  def update
    @media = Media.find(params[:id])
    @media.tag_list = params[:media][:tag_list]
    if request.post?
      if @media.update_attributes(:description => params[:media][:description], :category_id => params[:media][:category_id], :title => params[:media][:title])
        flash[:notice]="Media Updated"
        redirect_back_or_default :controller => '/media', :action => :show, :id => @media.id, :permalink => @media.permalink
      else
        render :action => :edit
      end
    end
  end
  def list
    @per_page = 15
    if params[:category].nil?
      @medias = Media.find(:all, :conditions => 'deleted_at is NULL and upload_complete = 1')
      @pages, @medias = paginate(:medias, {:conditions => 'deleted_at is NULL', :order => 'rating desc, created_at desc', :per_page => @per_page})
    else
      @category = Category.find(params[:category])
      @page_title = @category.name
      @medias = Media.find(:all, :conditions => ['deleted_at is NULL and category_id = ? and upload_complete = 1', params[:category]])
      @pages, @medias = paginate(:medias, {:conditions => ['deleted_at is NULL and category_id = ?', params[:category]], :order => 'rating desc, created_at desc', :per_page => @per_page})
    end
  end
  def search
    if !params[:query].nil?
      @query={:query=>params[:query]}
      @search_query = params[:query]
      @total, @medias = Media.full_text_search(@search_query, :page => (params[:page]||1), :conditions => 'deleted_at is NULL and upload_complete = 1')
      @pages = pages_for(@total)
    elsif !params[:tag].nil?
      @page_title = params[:tag].capitalize
      @per_page = 15
      @query={:tag=>params[:tag]}
      @tag = params[:tag]
      @tags = params[:tag].split.map {|o| CGI::unescape(o)}
      @medias = Media.find_tagged_with(@tags)
      @pages, @medias = paginate(:medias, {:conditions => ['tags.name = ? and deleted_at is NULL and upload_complete = 1', @tag], :order => 'rating desc, medias.created_at desc', :include => [:tags], :per_page => @per_page})
    else
      flash[:notice] = 'Please enter a search term.'
    end
  end
  def random
    @media = Media.find(:first, :conditions => 'deleted_at is NULL and upload_complete = 1', :order => 'RAND()')
    if (!@media.nil?)
      redirect_to :controller => 'media', :action => 'show', :id => @media.id, :permalink => @media.permalink
    else
      redirect_to :controller => 'media', :action => 'index'
    end
  end
  
  protected
  
  def do_video_conversion(highdef=false)
    if !@video_file.nil?
      @video_file.convert(highdef)
    end
  end
end
